package com.eedi.framework.logger.service;

import cn.hutool.core.util.StrUtil;
import com.eedi.framework.common.pojo.PageResult;
import com.eedi.framework.logger.controller.sys.vo.operatelog.SysOperateLogPageReq;
import com.eedi.framework.logger.controller.sys.vo.operatelog.SysOperateLogCreateReq;
import com.eedi.framework.logger.controller.sys.vo.operatelog.SysOperateLogResp;
import com.eedi.framework.logger.dal.mapper.SysOperateLogMapper;
import com.eedi.framework.logger.enmus.SysLogTypeEnum;
import com.eedi.sys.facade.SysUserFacade;
import com.eedi.sys.facade.TenantInfoFacade;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import com.eedi.framework.common.util.object.BeanUtils;
import javax.annotation.Resource;
import java.util.Collection;
import com.eedi.framework.logger.dal.dataobject.SysLogOperateDO;
import com.eedi.framework.common.util.string.StrUtils;

import static com.eedi.framework.common.util.collection.CollectionUtils.convertSet;
import static com.eedi.framework.logger.dal.dataobject.SysLogOperateDO.JAVA_METHOD_ARGS_MAX_LENGTH;
import static com.eedi.framework.logger.dal.dataobject.SysLogOperateDO.RESULT_MAX_LENGTH;
/**
 * 操作日志 Service 实现类
 *
 * @author 永聚长青源码
 */
@Service
@Validated
@Slf4j
public class SysOperateLogServiceImpl implements SysOperateLogService {

    @Resource
    private SysOperateLogMapper sysOperateLogMapper;
    @Resource
    private SysUserFacade sysUserFacade;
    @Resource
    private TenantInfoFacade tenantInfoFacade;

    @Override
    public void createOperateLog(SysOperateLogCreateReq createReqDTO) {
        SysLogOperateDO log = BeanUtils.toBean(createReqDTO, SysLogOperateDO.class);
        log.setJavaMethodArgs(StrUtils.maxLength(log.getJavaMethodArgs(), JAVA_METHOD_ARGS_MAX_LENGTH));
        log.setResultData(StrUtils.maxLength(log.getResultData(), RESULT_MAX_LENGTH));
        sysOperateLogMapper.insert(log);
    }

    @Override
    public PageResult<SysOperateLogResp> getOperateLogPage(SysOperateLogPageReq pageReqVO,String sysTenantId) {
        // 处理基于用户昵称的查询
        Collection<String> userIds = null;
        if (StrUtil.isNotEmpty(pageReqVO.getUserNickname())) {
            userIds = sysUserFacade.findUserName(pageReqVO.getUserNickname());
        }
        // 查询分页
        PageResult<SysOperateLogResp> result = sysOperateLogMapper.selectPage(pageReqVO, userIds, SysLogTypeEnum.OPERATER_LOG, sysTenantId);
        sysUserFacade.fillInUserName(result.getList(), SysOperateLogResp::getUserId, SysOperateLogResp::setUserNickname);
        sysUserFacade.fillInUserLoginId(result.getList(),SysOperateLogResp::getUserId,SysOperateLogResp::setSysUserAccountId);
        tenantInfoFacade.fillInTenantName(result.getList(),SysOperateLogResp::getTenantId,SysOperateLogResp::setTenantName);
        return result;
    }

}
